<template>

  <div class="event-container">

    <div class="content">

      <div class="search">
         <cq-region v-model="state.queryParams.regionCode"></cq-region>
        <van-dropdown-menu
          ref="menuRef"
          :close-on-click-overlay="false"
          :close-on-click-outside="false"
          > <van-dropdown-item ref="itemRef"
            > <template #title
              > <span class="filter-o"
                ><van-icon name="filter-o" size="20" /></span
              > </template
            >
            <div class="filter-content">
               <van-form ref="formRef"
                > <van-cell-group
                  > <van-field
                    v-model="state.queryParams.riskPoint"
                    label="预警点位名称"
                    label-align="top"
                    placeholder="请输入预警点位名称"
                  /> <van-field
                    v-model="state.formData.levelName"
                    label="告警等级"
                    @click="querySelect('warningLevel')"
                    placeholder="请选择降雨轮次"
                    readonly
                    label-align="top"
                    right-icon="arrow-down"
                    style="width: 50%"
                  /> <van-field
                    v-model="state.formData.timeRange"
                    @click="state.datePicker2 = true"
                    label="告警日期"
                    placeholder="请选择时间范围"
                    readonly
                    label-align="top"
                    right-icon="arrow-down"
                    style="width: 50%"
                  /> <van-field
                    v-model="state.formData.isDrillName"
                    name="region"
                    label="是否演练"
                    @click="querySelect('isDrill')"
                    style="width: 50%"
                    readonly
                    label-align="top"
                    right-icon="arrow-down"
                    placeholder="请选择是否演练"
                  /> </van-cell-group
                > </van-form
              >
            </div>

            <div style="padding: 5px 10px">
               <van-button type="primary" block @click="onFirm">确认</van-button
              > <van-button style="margin-top: 5px" block @click="onReset"
                >重置</van-button
              >
            </div>
             </van-dropdown-item
          > </van-dropdown-menu
        >
      </div>

    </div>

    <div class="button-group">
       <van-button
        round
        :type="state.active == item.name ? 'primary' : 'default'"
        v-for="(item, index) in state.buttonGroup"
        :key="index"
        @click="handleChange(item.name)"
        style="margin-right: 12px"
        >{{ item.name }}</van-button
      >
    </div>

    <div class="alarm-list" ref="listContainer">
       <van-pull-refresh v-model="refreshing" @refresh="onLoad('refresh')"
        > <van-list
          v-model:loading="loading"
          :finished="finished"
          finished-text="没有更多了"
          @load="onLoad"
          >
          <div
            class="alarm-item"
            v-for="(item, index) in state.alarmList"
            :key="index"
            @click="goDetails(item)"
          >

            <div class="alarm-header">
               <span class="t1">{{ item.districtName }}</span
              > <span
                class="t3"
                :style="{
                  color: getColor(item.level),
                  borderColor: getColor(item.level),
                }"
                >{{ MAP_STATE.level[item.level] }}</span
              > <span class="t2" v-if="item.isDrill == 1">演练</span>
              <div
                class="t4"
                :style="{
                  color: item.state == '1' ? 'rgba(0,0,0,0.4)' : '#FC9C00',
                  borderColor:
                    item.state == '1' ? 'rgba(0,0,0,0.4)' : '#FC9C00',
                }"
              >
                 {{ item.state == '1' ? '待处置' : '处置中' }}
              </div>

            </div>

            <div class="alarm-content">

              <div class="c2"> {{ item.riskPoint }} </div>

              <div class="line"></div>

              <div class="status">

                <div>
                   <span>{{ MAP_STATE.type[item.type] }}</span
                  >
                </div>

                <div>{{ formattedDate(item.createTime) }}</div>

              </div>

              <div class="confirm">
                 <van-button
                  type="success"
                  block
                  @click.stop="eventComplete(item)"
                  :disabled="item.state == '1'"
                  >事件办结</van-button
                > <van-button
                  type="primary"
                  block
                  @click.stop="createOrder(item)"
                  >创建工单</van-button
                >
              </div>

            </div>

          </div>
           </van-list
        > </van-pull-refresh
      >
    </div>
     <van-overlay :show="state.show" style="z-index: 2000"
      >
      <div class="wrapper">

        <div class="block">
           <!-- <div class="title" v-if="state.completeEvent.complete == 0">确认办结事件</div>
          <div
            class="title"
            v-else-if="state.completeEvent.complete == 1"
            style="color: red"
          >
            存在未办结工单请确认
          </div>
          <div class="title" v-else style="color: red">本事件未创建工单无法办结</div> -->

          <div class="title">是否办结</div>

          <div class="buttons">
             <van-button
              style="background-color: #e6f7ff; color: #1890ff; width: 50%"
              @click="state.show = false"
              >取消</van-button
            > <van-button
              type="success"
              style="width: 50%"
              @click="handleConfirm"
              >确认办结</van-button
            >
          </div>

        </div>

      </div>
       </van-overlay
    > <van-popup
      v-model:show="state.showPicker"
      destroy-on-close
      position="bottom"
      > <van-picker
        :columns="state.columns"
        :model-value="state.pickerValue"
        @confirm="onPicker"
        @cancel="state.showPicker = false"
      /> </van-popup
    > <van-popup
      v-model:show="state.datePicker2"
      destroy-on-close
      position="bottom"
      > <van-picker-group
        title="告警日期"
        :tabs="['开始日期', '结束日期']"
        @confirm="changeQTime"
        @cancel="state.datePicker2 = false"
        > <van-date-picker
          v-model="state.formData.startDate"
          :min-date="minDate"
          :max-date="maxDate"
        /> <van-date-picker
          v-model="state.formData.endDate"
          :min-date="minDate"
          :max-date="maxDate"
        /> </van-picker-group
      > </van-popup
    >
  </div>

</template>

<script setup>
  import { reactive, ref, onMounted } from 'vue'
  import locationIcon from '@/assets/images/task/icon_region_location.png'
  import { getDisposeEventListApi, completedWorkApi } from '@/api/eventTask'
  import { showFailToast, showSuccessToast } from 'vant'
  import moment from 'moment'
  import CqRegion from '@/components/CqRegion.vue'
  import { getDictDataApi } from '@/api/common'
  const state = reactive({
    active: '待处置',
    buttonGroup: [
      {
        name: '待处置',
      },
      {
        name: '处置中',
      },
    ],
    alarmList: [],
    show: false,
    completeEvent: {},
    queryParams: {
      alarmType: '1',
      pageNum: 1,
      pageSize: 10,
      state: '1', // 1:待处置 2:处置中
    },
    pages: 0,
    formData: {},
  })
  import { useRouter } from 'vue-router'
  const router = useRouter()
  const maxDate = new Date(2025, 11, 31) //最大日期
  const minDate = new Date(2025, 0, 1) //最小日期
  // 分页参数
  const refreshing = ref(false)
  const loading = ref(false)
  const finished = ref(false)

  const listContainer = ref(null)
  // 点击预警按钮
  const handleChange = (val) => {
    state.active = val
    // state.queryParams.pageNum = 1;
    state.queryParams = {
      pageNum: 1,
      pageSize: 10,
      alarmType: '1',
      state: state.active == '待处置' ? '1' : '2',
    }
    getDisposeEventListFn()
    state.pickerValue = []
    state.pickerType = ''
    state.columns = []
    state.formData = {}
    // if (val == "待处置") {
    //   state.queryParams.state = "1";
    //   getDisposeEventListFn();
    // } else {
    //   state.queryParams.state = "2";
    //   getDisposeEventListFn();
    // }

    // 滚动到顶部
    listContainer.value.scrollTop = 0
  }

  // 点击确认呼应
  const handleConfirm = () => {
    // state.show = false;
    completedWorkApi(state.completeEvent.id).then(({ data }) => {
      if (data.code == 500) {
        showFailToast(data.message)
      } else if (data.code == 200) {
        showSuccessToast('办结成功')
      }
    })
  }

  // 事件办结
  const eventComplete = (item) => {
    state.show = true

    state.completeEvent = item
  }

  // 创建工单
  const createOrder = (item) => {
    localStorage.setItem('orderDetail', JSON.stringify(item))
    router.push({
      path: '/disposeEventCreateOrder',
      query: {
        riskPointId: item.riskPointId,
        level: item.level,
        id: item.id,
      },
    })
  }

  // 获取处置事件列表
  const getDisposeEventListFn = () => {
    getDisposeEventListApi(state.queryParams)
      .then(({ data }) => {
        if (data && data.code == 200) {
          state.pages = Math.ceil(data.data.total / state.queryParams.pageSize)

          let list = data.data.list || []

          if (state.queryParams.pageNum == 1) {
            state.alarmList = list
          } else {
            state.alarmList = state.alarmList.concat(list)
          }
          if (state.queryParams.pageNum == state.pages || state.pages == 0) {
            finished.value = true
          }
        } else {
          finished.value = true
        }
      })
      .catch((err) => {
        finished.value = true
      })
      .finally(() => {
        loading.value = false
      })
  }

  const onLoad = (type) => {
    if (type === 'refresh') {
      finished.value = false
      loading.value = true
    }

    if (refreshing.value || type === 'refresh') {
      state.pages = 0
      state.queryParams.pageNum = 1
      state.alarmList.value = []
      refreshing.value = false
    }

    if (type !== 'refresh') {
      if (state.queryParams.pageNum >= state.pages) return
      state.queryParams.pageNum++
    }
    getDisposeEventListFn()
  }
  // 状态映射
  const MAP_STATE = {
    // 风险等级
    level: {
      3: '低风险',
      2: '中风险',
      1: '高风险',
    },
    // 告警类型
    type: {
      1: '物联网',
      2: '视频AI',
      3: '人工',
    },
    // 是否演练
    isDrill: {
      0: '否',
      1: '是',
    },
  }

  // 根据状态返回颜色
  const getColor = (key) => {
    switch (key) {
      case '3':
        return '#00b042'
      case '2':
        return '#FC9C00'
      case '1':
        return '#FF4D4F'
      default:
        break
    }
  }

  // 跳转详情
  const goDetails = (item) => {
    router.push({
      path: '/disposeEventDetail',
      query: {
        id: item.id,
      },
    })
  }

  const formattedDate = (date) => {
    return moment(date).format('MM/DD HH:mm')
  }
  // 预警等级下拉
  const warningLevelOptions = ref([])
  // 获取预警等级
  const getWarningLevelOptions = async () => {
    const { data } = await getDictDataApi('sys_warn_level')
    if (data && data.code == 200) {
      warningLevelOptions.value =
        data.data.map((item) => ({
          ...item,
          text: item.dictlabel, // 或者字段名取决于接口返回结构
          value: item.dictvalue,
        })) || []
    }
  }

  // 是否演练
  const isDrillOptions = [
    {
      text: '否',
      value: '0',
    },
    {
      text: '是',
      value: '1',
    },
  ]

  // 点击查询条件
  const querySelect = (type) => {
    if (type === 'haveWork') {
      state.columns = haveWorkOptions
    } else if (type === 'warningLevel') {
      state.columns = warningLevelOptions.value
    } else if (type === 'isDrill') {
      state.columns = isDrillOptions
    }
    state.showPicker = true
    state.pickerType = type
  }

  // 选择下拉弹窗
  const onPicker = ({ selectedValues, selectedOptions }) => {
    switch (state.pickerType) {
      case 'haveWork':
        state.queryParams.haveWork = selectedOptions[0].value
        state.formData.haveWorkName = selectedOptions[0].text
        break
      case 'isDrill':
        // state.formData.isDrill = selectedValues[0].value;
        state.queryParams.isDrill = selectedOptions[0].value
        state.formData.isDrillName = selectedOptions[0].text
        break
      case 'warningLevel':
        state.queryParams.level = selectedOptions[0].value
        state.formData.levelName = selectedOptions[0].text
        break
      default:
        break
    }
    //分类型选择器确定
    state.pickerValue = selectedValues
    state.showPicker = false
  }

  // 自定义时间选择
  const changeQTime = (val) => {
    const start = `${val[0].selectedValues.join('-')}`
    const end = `${val[1].selectedValues.join('-')}`
    if (new Date(start) > new Date(end)) {
      showFailToast('开始时间不能大于结束时间')
      return
    }
    state.formData.timeRange = start + ' - ' + end
    state.queryParams.startTime = start
    state.queryParams.endTime = end
    state.datePicker2 = false
  }
  const menuRef = ref(null)
  // 确认
  const onFirm = () => {
    state.queryParams.pageNum = 1
    getDisposeEventListFn()
    menuRef.value.close()
  }

  // 重置
  const onReset = () => {
    state.queryParams = {
      pageNum: 1,
      pageSize: 10,
      alarmType: '1',
      state: state.active == '待处置' ? '1' : '2',
    }
    state.pickerValue = []
    state.pickerType = ''
    state.columns = []
    state.formData = {}
    getDisposeEventListFn()
    menuRef.value.close()
  }

  onMounted(() => {
    getDisposeEventListFn()
    getWarningLevelOptions()
  })
</script>

<style lang="less" scoped>
  .event-container {
  height: 100%;
  .content {
    background: rgba(243, 243, 243, 1);
    margin-bottom: 10px;
    .search {
      height: 30px;
      display: flex;
      justify-content: space-between;
      .van-field {
        width: calc(100% - 40px);
        background: #fff;
        height: 100%;
        display: flex;
        align-items: center;
        padding: 0 10px;
        margin-bottom: 10px;
      }
      :deep(.van-dropdown-menu__bar) {
        background: #fff;
        margin-left: 10px;
        height: 30px;
        width: 30px;
        .van-dropdown-menu__title {
          padding: 0;
        }
        .van-dropdown-menu__title:after {
          display: none;
        }
        .van-dropdown-menu__title--down:after {
          display: none;
        }
      }
      :deep(.van-dropdown-item) {
        top: 150px !important;
      }
      .filter-o {
        height: 30px;
        width: 30px;
        display: flex;
        align-items: center;
        justify-content: center;
      }
      .filter-content {
        padding: 10px 0;
        width: 100%;
        .van-form {
          display: flex;
          flex-wrap: wrap;
        }
        :deep(.van-cell-group) {
          display: flex;
          flex-wrap: wrap;
        }
        :deep(.van-field) {
          width: 100%;
          height: auto;
          .van-field__value {
            background: #f2f2f2;
            height: 40px;
            display: flex;
            align-items: center;
            padding: 0 10px;
            .van-field__body {
              width: 100%;
            }
          }
        }
      }
    }
  }
  .alarm-list {
    margin-top: 12px;
    // height: calc(100% - 50px);
    height: 100%;
    overflow-y: auto;
    .alarm-item {
      background: #ffffff;
      border-radius: 8px 8px 8px 8px;
      margin-bottom: 12px;
      .alarm-header {
        height: 36px;
        width: 100%;
        background: linear-gradient(
          90deg,
          rgba(0, 127, 255, 0.08) 0%,
          rgba(0, 127, 255, 0) 100%
        );
        display: flex;
        padding-top: 4px;
        padding-left: 12px;
        padding-right: 12px;
        box-sizing: border-box;
        span {
          margin-top: 2px;
        }
        font-family: PingFang TC, PingFang TC;

        .t1 {
          font-weight: 600;
          font-size: 16px;
          color: rgba(0, 0, 0, 0.9);
          margin-left: 4px;
        }

        .t2 {
          font-weight: 400;
          font-size: 12px;
          color: rgba(0, 0, 0, 0.6);
          // margin-left: 12px;
          border: 1px solid #08d2d2;
          color: #08d2d2;
          padding: 0 4px;
          border-radius: 4px 4px 4px 4px;
          height: 18px;
          margin-left: 4px;
          margin-top: 5px;
        }

        .t3 {
          border-radius: 4px 4px 4px 4px;
          border: 1px solid #00b042;
          color: #00b042;
          text-align: center;
          padding: 0 4px;
          height: 18px;
          margin-left: 8px;
          margin-top: 5px;
        }

        .t4 {
          border-radius: 4px 4px 4px 4px;
          border: 1px solid rgba(0, 0, 0, 0.4);
          color: rgba(0, 0, 0, 0.4);
          text-align: center;
          padding: 0 4px;
          height: 18px;
          margin-left: 8px;
          margin-top: 5px;
          margin-left: auto;
        }
      }

      .alarm-content {
        padding: 8px 12px 12px 12px;
        font-family: PingFang TC, PingFang TC;
        .c1 {
          font-weight: 600;
          font-size: 16px;
          color: rgba(0, 0, 0, 0.9);
        }

        .c2 {
          font-weight: 400;
          font-size: 14px;
          color: rgba(0, 0, 0, 0.6);
          margin-top: 4px;
        }

        .line {
          border: 1px solid #e7e7e7;
          margin: 8px 0;
        }

        .status {
          display: grid;
          grid-template-columns: repeat(3, 1fr);
          gap: 8px 18px;
          font-family: PingFang TC, PingFang TC;
          font-weight: 400;
          font-size: 12px;
          color: rgba(0, 0, 0, 0.4);
          span {
            color: #007fff;
          }
          div:last-child {
            grid-column: span 2; // 可调整为 span 2 或 span 3 来占用更多列
            width: 100%; // 根据需要可选
            text-align: right;
          }
        }
        .confirm {
          width: 100%;
          margin-top: 8px;
          display: flex;
          gap: 8px;
        }
      }
    }
  }
}

.wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;

  .block {
    width: 300px;
    // height: 160px;
    background: #ffffff;
    border-radius: 12px 12px 12px 12px;
    padding: 24px;
    box-sizing: border-box;
    text-align: center;
    .title {
      font-family: PingFang TC, PingFang TC;
      font-weight: 600;
      font-size: 18px;
      color: rgba(0, 0, 0, 0.9);
    }

    .buttons {
      margin-top: 24px;
      display: flex;
      gap: 12px;
    }
  }
}
</style>

